import { type LoaderFunctionArgs } from "@remix-run/node";

// Minimal HTML page that posts the code back to the opener window then closes.
export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const code = url.searchParams.get("code") || "";
  const state = url.searchParams.get("state") || "";
  const shop = url.searchParams.get("shop") || "";
  const forward = url.searchParams.get("forward") || "";
  const method = (url.searchParams.get("method") || "").toLowerCase();

  const html = `<!DOCTYPE html>
<html>
  <head><meta charset=\"utf-8\" /><title>OAuth Capture</title></head>
  <body>
    <script>
      (function() {
        try {
          var payload = { type: 'shopify_oauth_code', code: ${JSON.stringify(code)}, state: ${JSON.stringify(state)}, shop: ${JSON.stringify(shop)} };
          if (window.opener) {
            window.opener.postMessage(payload, '*');
          } else if (window.parent) {
            window.parent.postMessage(payload, '*');
          }
        } catch (e) {}
        try {
          var forward = ${JSON.stringify(forward)};
          var method = ${JSON.stringify(method)};
          if (forward) {
            var params = new URLSearchParams({ code: ${JSON.stringify(code)}, state: ${JSON.stringify(state)}, shop: ${JSON.stringify(shop)} });
            if (method === 'post') {
              var form = document.createElement('form');
              form.method = 'POST';
              form.action = forward;
              ['code','state','shop'].forEach(function(k){
                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = k;
                input.value = params.get(k);
                form.appendChild(input);
              });
              document.body.appendChild(form);
              form.submit();
              return;
            } else {
              // default GET forward with query string
              window.location.replace(forward + (forward.indexOf('?')>-1?'&':'?') + params.toString());
              return;
            }
          }
        } catch (e) {}
        try { window.close(); } catch (e) {}
      })();
    </script>
  </body>
</html>`;

  return new Response(html, {
    headers: {
      'Content-Type': 'text/html; charset=utf-8',
      'Cache-Control': 'no-store',
    },
  });
};


